//
//  HJSelectFridendsController.m
//  KaiChat
//
//  Created by lx on 2023/11/2.
//

#import "HJSelectFridendsController.h"
#import "HJSelectFridendCell.h"
#import "HJSectionHeaderView.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "QMUITextField.h"
#import "HJAddFriendController.h"
#import "HJNavigationController.h"
#import "HJSelectMemberView.h"
#import "HJChatController.h"
#import "HJChatGroupModel.h"
#import "TJEmptyDataHandler.h"
#import "HJOrderedDictionary.h"
#import "HJGroupMemberModel.h"
#import "HJSearchView.h"
#import "UITableView+SCIndexView.h"

@interface HJSelectFridendsController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *sortKeys;
@property (nonatomic, strong) HJOrderedDictionary *userDict;
@property (nonatomic, strong) NSMutableArray *searchDatas;
@property (nonatomic, strong) NSArray *originalDatas;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, strong) HJChatGroupModel *groupModel;
@property (nonatomic, weak) HJSelectMemberView *selectMemberView;
@property (nonatomic, weak) HJBarButton *doneButton;
@property (nonatomic, weak) UIView *searchView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, assign) NSInteger count;


@end

@implementation HJSelectFridendsController


- (void)showInController:(UIViewController *)controller {
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:self];
    [controller presentViewController:navController animated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
        
    
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor font:UIFontMediumMake(14) target:self action:@selector(didClickDoneButton:)];
    doneButton.enabled = NO;
    [doneButton setTitleColor:UIColor.tj_mainColor forState:UIControlStateNormal];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [self.navigationBar.contentView addSubview:doneButton];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    _doneButton = doneButton;
    
    UIView *headerView = [UIView addToView:self.view];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.height.offset(60);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
 
    QMUITextField *textField = searchView.textField;
    textField.placeholder = @"Search";
    textField.maximumTextLength = 30;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = textField;
    
    TJWeakify(self)
    HJSelectMemberView *selectMemberView = [HJSelectMemberView addToView:headerView];
    [selectMemberView setDidClickDeleteButtonBlock:^(HJChatFriendModel * _Nonnull model) {
        [weakself didSelectRowWithModel:model];
    }];
    [selectMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
    _headerView = headerView;
    _selectMemberView = selectMemberView;
    _searchView = searchView;
    
    self.navigationBar.title = @"Select Fridends";
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJSelectFridendCell.class forCellReuseIdentifier:@"HJSelectFridendCell"];
    [self.tableView registerClass:HJSectionHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJSectionHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
    
    SCIndexViewConfiguration *configuration = [SCIndexViewConfiguration configuration];
    configuration.indicatorBackgroundColor = UIColor.tj_mainColor;
    configuration.indicatorTextFont = UIFontMediumMake(20);
    configuration.indexItemTextColor = UIColor.tj_BEBDCAColor;
    configuration.indexItemTextFont = UIFontMediumMake(12);
    configuration.indexItemSelectedTextFont = UIFontMediumMake(12);
    configuration.indexItemSelectedTextColor = UIColor.tj_BEBDCAColor;
    configuration.indexItemSelectedBackgroundColor = UIColor.clearColor;
    self.tableView.sc_indexViewConfiguration = configuration;
    self.tableView.sc_translucentForTableViewInNavigationBar = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    [self loadData];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;
    
    if (isEmptyString(keyword)) {
        for (HJChatFriendModel *obj in self.originalDatas) {
            obj.nameAttributedstring = nil;
        }
        self.emptyDataHandler.canDisplay = YES;
        [self.searchDatas removeAllObjects];
        [self handleModels:self.originalDatas];
        return;
    }
    
    self.emptyDataHandler.canDisplay = NO;
    [self.searchDatas removeAllObjects];
    for (HJChatFriendModel *obj in self.originalDatas) {
            NSRange range = [obj.nickname rangeOfString:keyword options:NSCaseInsensitiveSearch];
            if (range.location != NSNotFound) {
                
                NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.nickname];
                [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
                obj.nameAttributedstring = attrStr;
                [self.searchDatas addObject:obj];
            } else {
                obj.nameAttributedstring = nil;
            }
    }
    [self handleModels:self.searchDatas];
}

- (void)didClickDoneButton:(UIButton *)button {
    
    [HJHUD showLoadingInView:self.view];

    if (self.memberUserIds.count) {//添加
        [HJIM.shareIM.groupManager inviteFridendJoinGroupByGroupId:self.groupId userModels:self.userDict.allValues completion:^(NSError * _Nullable error) {
            if (error) {
                if (error.code == 1600 || error.code == 1601) {
                    [HJHUD showErrorMessage:error.localizedFailureReason];
                } else {
                    [HJHUD showErrorMessageTip];
                }
                return;
            }
            if (self.complete) {
                self.complete();
            }
            [self dismissToRootViewController:YES completion:nil];
            [HJHUD showSucceedMessageTip];
        }];
        return;
    }
    
    [HJIM.shareIM.groupManager createGroupWithUserIds:self.userDict.allKeys completion:^(HJChatGroupModel * _Nullable groupModel, NSError * _Nullable error) {
        
        if (groupModel) {
            [self dismissToRootViewController:YES completion:^{
                HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:toString(groupModel.groupId) sessionUserd:nil chatType:HJChatTypeGroup sessionName:groupModel.name];
                HJChatController *chatController = [HJChatController chatControllerWithSessionModel:sessionModel];
                [[HJTools currentNavController] pushViewController:chatController];
                [HJHUD showSucceedMessageTip];
            }];
        } else {
            if (error.code == 1600 || error.code == 1601) {
                [HJHUD showErrorMessage:error.localizedFailureReason];
            } else {
                [HJHUD showErrorMessageTip];
            }
        }
    }];
}

- (void)didClickNewFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJApplyListController"];
}
 
- (nullable HJSelectFridendCell *)getVisibleCellWithModel:(HJChatFriendModel *)model {
    for (HJSelectFridendCell *cell in self.tableView.visibleCells) {
        if ([cell.model.userId isEqualToString:model.userId]) {
            return cell;
        }
    }
    return nil;
}


- (void)loadData {
    [[HJIM shareIM].userManager getFriendListsComplete:^(NSArray<HJChatFriendModel *> * _Nullable datas) {

        self.originalDatas = datas;
            
        dispatch_async_main_queue(^{
            self.emptyDataHandler.canDisplay = YES;
            [self hiddenLoading];
            [self handleModels:datas];
        });
    }];
    
    dispatch_async_sql_queue(^{
        [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {
            self.groupModel = groupModel;
        }];
    });
}
 
- (void)updateSelectState:(HJChatFriendModel *)obj {//只设置之前选中的, 默认选中的不处理
    HJChatFriendModel *addFriendModel = [self.userDict objectForKey:obj.userId];
    obj.isSelect = addFriendModel.isSelect;

    if (obj.isSelect) {
        [self.userDict setObject:obj forKey:obj.userId];
    }
}

- (void)handleModels:(NSArray *)models {
    
    for (HJChatFriendModel *model in models) {
        model.isJoin = [self.memberUserIds containsObject:model.userId];
        if (model.isJoin) {
            model.isSelect = YES;
        }
    }
    
    self.count = self.memberUserIds.count;
    
    NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
    for (HJChatFriendModel *obj in models) {
        
        if (TJIM_isSelf(obj.userId)) {
            continue;
        }
        
        if (!obj.isJoin) {
            [self updateSelectState:obj];
        }
        
        NSString *displayName = obj.showName;
        NSString *firstLetter = [displayName.firstPinYin uppercaseString];
        if (firstLetter.length == 0 || !isalpha([firstLetter characterAtIndex:0])) {
            firstLetter = @"#";
        }
        NSMutableArray *dictMarr = [mainDict valueForKey:firstLetter];
        if (!dictMarr) {
            [mainDict setValue:[NSMutableArray array] forKey:firstLetter];
            dictMarr = [mainDict valueForKey:firstLetter];
        }
        [dictMarr addObject:obj];
    }
    NSArray *nonameList = [mainDict valueForKey:@"#"];
    if (nonameList) {
        [mainDict removeObjectForKey:@"#"];
    }
    
    [self.datas removeAllObjects];
    [self.sortKeys removeAllObjects];
    
    NSArray *sortKeys = [mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
 
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.datas addObject:@{ @"title": obj, @"datas": mainDict[obj]}];
    }];
    
    self.sortKeys = [NSMutableArray arrayWithArray:sortKeys];
    if (nonameList.count) {
        [self.sortKeys addObject:@"#"];
        [self.datas addObject:@{@"title": @"#", @"datas": nonameList}];
    }
    
    self.tableView.sc_indexViewDataSource = self.sortKeys;
    [self.tableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section][@"datas"];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJSelectFridendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJSelectFridendCell" forIndexPath:indexPath];
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    if (model.isJoin) return;
    
    [self didSelectRowWithModel:model];
}

- (void)didSelectRowWithModel:(HJChatFriendModel *)model {
    
    model.isSelect = !model.isSelect;
    
    HJSelectFridendCell *cell = [self getVisibleCellWithModel:model];
    cell.model = model;
    if (model.isSelect) {
        [self.userDict setObject:model forKey:model.userId];
    } else {
        [self.userDict removeObjectForKey:model.userId];
    }
    
    [self updateDoneTitle];
    [self updateSelectMemberViewHeight];
}


- (void)updateSelectMemberViewHeight {
    execute(^{
        if (self.userDict.count > 0) {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(140);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(80);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
        } else {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(60);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(0);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
    
        }
    }, ^{
        self.selectMemberView.datas = self.userDict.allValues;
    });
}

- (void)updateDoneTitle {
    if (self.userDict.count > 0) {
        if (self.memberUserIds.count) {
            _doneButton.enabled = self.userDict.count > 0;
        } else {
            _doneButton.enabled = self.userDict.count > 1;
        }
        [_doneButton setTitle:[NSString stringWithFormat:@"Done(%ld)", self.userDict.count] forState:UIControlStateNormal];
    } else {
        _doneButton.enabled = NO;
        [_doneButton setTitle:@"Done" forState:UIControlStateNormal];
    }
    [_doneButton sizeToFit];
    CGFloat doneButtonW = MAX(_doneButton.tj_width + 10, 40);
    [_doneButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(doneButtonW);
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}
 
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJSectionHeaderView"];
    view.titleLabel.text = @"";
    view.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    view.backgroundColor = UIColor.tj_F6F6F6Color;
    NSString *sectionTitle = self.datas[section][@"title"];
    view.titleLabel.text = sectionTitle;
    view.titleLabel.textColor = UIColor.tj_BEBDCAColor;
    view.titleLabel.font = UIFontMake(12);
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)sortKeys {
    if (!_sortKeys) {
        _sortKeys = [NSMutableArray array];
    }
    return _sortKeys;
}

- (HJOrderedDictionary *)userDict {
    if (!_userDict) {
        _userDict = [HJOrderedDictionary dictionary];
    }
    return _userDict;
}
 
- (NSMutableArray *)searchDatas {
    if (!_searchDatas) {
        _searchDatas = [NSMutableArray array];
    }
    return _searchDatas;
}

@end

